package com.ruoyi.canteen.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.storage.model.DefaultPutRet;
import com.ruoyi.canteen.domain.CanteenCpClass;
import com.ruoyi.canteen.domain.CanteenMd;
import com.ruoyi.canteen.service.ICanteenCpClassService;
import com.ruoyi.canteen.service.ICanteenMdService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.QiniuUtil;
import com.ruoyi.common.utils.ServletUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.canteen.domain.CanteenCp;
import com.ruoyi.canteen.service.ICanteenCpService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 菜品Controller
 * 
 * @author ruoyi
 * @date 2021-09-08
 */
@RestController
@RequestMapping("/canteen/cp")
public class CanteenCpController extends BaseController
{
    @Autowired
    private ICanteenCpService canteenCpService;

    @Autowired
    private ICanteenCpClassService canteenCpClassService;

    @Autowired
    private ICanteenMdService canteenMdService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private QiniuUtil qiniuUtil;



    /**
     * 查询菜品列表
     */
    @PreAuthorize("@ss.hasPermi('canteen:cp:list')")
    @GetMapping("/list")
    public AjaxResult list(CanteenCp canteenCp)
    {
        startPage();
        List<CanteenCp> list = canteenCpService.selectCanteenCpList(canteenCp);
        //return getDataTable(list);
        Map<String, Object> map = new HashMap<>();
        map.put("cpList", getDataTable(list));
        CanteenCpClass cpClass = new CanteenCpClass();
        cpClass.setDeleteFlag(1);
        map.put("classList", canteenCpClassService.selectCanteenCpClassList(cpClass));
        return AjaxResult.success(map);
    }



    @PostMapping("/import")
    public AjaxResult importData(@RequestParam("file") MultipartFile[] file, String cpId) throws IOException
    {
        int count=0;
        String url="";
        try {
             DefaultPutRet putRet = null;

             String[] ss = {};
             DateUtils dateUtils = new DateUtils();
             LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
             for (MultipartFile multipartFile : file) {

                 /*
                 //传多个照片
                 ss  = multipartFile.getOriginalFilename().split("\\.");
                putRet  = qiniuUtil.upload(multipartFile.getBytes(), cpId+"-"+DateUtils.dateTimeNow()+"."+ss[1]);
                //上传成功后获取url
                if(putRet !=null && putRet.hash != null)
                {
                   url += qiniuUtil.getFileDomain()+"/"+putRet.key+",";
                }
                 * */
                 //传单张照片
                 putRet  = qiniuUtil.upload(multipartFile.getBytes(),   loginUser.getDeptId()+"-"+ cpId+".jpg");
                 url = qiniuUtil.getFileDomain()+"/"+putRet.key+",";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败,失败原因:"+e.getMessage());
        }

        return AjaxResult.success(url);
    }

    /**
     * 导出菜品列表
     */
    @PreAuthorize("@ss.hasPermi('canteen:cp:export')")
    @Log(title = "菜品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(CanteenCp canteenCp)
    {
        List<CanteenCp> list = canteenCpService.selectCanteenCpList(canteenCp);
        ExcelUtil<CanteenCp> util = new ExcelUtil<CanteenCp>(CanteenCp.class);
        return util.exportExcel(list, "菜品数据");
    }

    /**
     * 获取菜品详细信息
     */
    @PreAuthorize("@ss.hasPermi('canteen:cp:query')")
    @GetMapping(value = "/{id}")
    public CanteenCp getInfo(@PathVariable("id") Long id)
    {

        CanteenCp cp =  canteenCpService.selectCanteenCpById(id);
        //cp.setCpClasses(canteenCpService.getCanteenCpClassById(cp.getId()));
        //cp.setCpSpecials(canteenCpService.getCanteenCpSpecialsById(cp.getId()));

        //return (canteenCpService.getCanteenCpById(id));

        /*
        Map<String, Object> map = new HashMap<>();
        map.put("cpInfo", canteenCpService.selectCanteenCpById(id));
        map.put("classList", canteenCpClassService.selectCanteenCpClassList(new CanteenCpClass()));
        return AjaxResult.success(map);
        * */
        return cp;
    }

    /**
     * 新增菜品
     */
    @PreAuthorize("@ss.hasPermi('canteen:cp:add')")
    @Log(title = "菜品", businessType = BusinessType.INSERT)
    @PostMapping
    //public AjaxResult add(@RequestBody CanteenCp canteenCp)
    //public AjaxResult add(@RequestBody Map<Object, Object> models)
    //public AjaxResult add(@RequestParam(value = "form", required = false) CanteenCp form, @RequestParam("file") MultipartFile[] file)
    public AjaxResult add(@RequestParam("file") MultipartFile[] file, HttpServletRequest request)
    {
        int rtn=0;
        String url = "";
        DefaultPutRet putRet = null;
        String form = request.getParameter("canteenForm");
        JSONObject userJson = JSONObject.parseObject(form);
        CanteenCp cp = JSONObject.toJavaObject(userJson,CanteenCp.class);



        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        CanteenMd md = null;
        if(loginUser.getDeptId() != null)
        {
            cp.setDeptId(loginUser.getDeptId());
            //获取门店id
            md =  canteenMdService.selectCanteenMdByDeptId(loginUser.getDeptId());
            if(md != null)
                cp.setMdId(md.getMdId());
        }





        try {

            for (MultipartFile f : file)
            {
                putRet  = qiniuUtil.upload(f.getBytes(), loginUser.getDeptId()+"-"+ DateUtils.dateTimeNow()+".jpg");
                url += putRet.key+",";
            }
            cp.setUrl(url);
            rtn  =   canteenCpService.insertCanteenCp(cp);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return toAjax(rtn);
    }

    /**
     * 修改菜品
     */
    @PreAuthorize("@ss.hasPermi('canteen:cp:edit')")
    @Log(title = "菜品", businessType = BusinessType.UPDATE)
    @PutMapping
    //public AjaxResult edit(@RequestBody CanteenCp canteenCp)
    public AjaxResult edit(@RequestParam("file") MultipartFile[] file, HttpServletRequest request)
    {
        String form = request.getParameter("canteenForm");
        JSONObject userJson = JSONObject.parseObject(form);
        CanteenCp cp = JSONObject.toJavaObject(userJson,CanteenCp.class);
        int rtn = 0;
        CanteenMd md = null;
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if(loginUser.getDeptId() != null)
            {
                cp.setDeptId(loginUser.getDeptId());
                //获取门店id
                md =  canteenMdService.selectCanteenMdByDeptId(loginUser.getDeptId());
                if(md != null)
                    cp.setMdId(md.getMdId());
            }




                //修改图片
                if(file.length>0)
                {
                    String url = "";
                    DefaultPutRet putRet = null;
                    //删除旧图片
                    String[] delUrls = cp.getUrl().split(",");
                    try{
                        if(delUrls.length>0)
                        {
                            for(int i=0;i<delUrls.length;i++)
                            {
                                qiniuUtil.delete(delUrls[0]);
                            }

                        }
                    }catch (Exception ex)
                    {
                        System.out.println(ex);

                    }

                    try{
                        //插入新图片
                        for (MultipartFile f : file)
                        {
                            putRet  = qiniuUtil.upload(f.getBytes(), loginUser.getDeptId()+"-"+ DateUtils.dateTimeNow()+".jpg");
                            url += putRet.key+",";
                        }
                        cp.setUrl(url);

                    }catch (Exception ex)
                    {
                        System.out.println(ex);
                    }

                }
        try {
            rtn= canteenCpService.updateCanteenCp(cp);
        } catch (Exception e) {
            e.printStackTrace();
        }


        /*
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if(loginUser.getDeptId() != null)
                canteenCp.setDeptId(loginUser.getDeptId());
            canteenCpService.updateCanteenCp(canteenCp);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        * */
        return toAjax(rtn);
    }

    /**
     * 删除菜品
     */
    @PreAuthorize("@ss.hasPermi('canteen:cp:remove')")
    @Log(title = "菜品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(canteenCpService.deleteCanteenCpByIds(ids));
    }
}
